# encoding:utf-8
'''
@author:  adog
@Email   :
Created on 2021-03-27 16:19:08
'''
import numpy as np
import pandas as pd
import json
import dataMan as DM
import apps.adog.util.mdbcom as mdbcom
import apps.adog.util.dbcom as dbcom
import util.xtool as xtool

class Analysis():
    def __init__(self,):
        self.data=None
        
    def loadData(self,dataMan=None,cod=[],startDate='2020-01-01',freq='1d',db='mongo'):
        dm=None
        if dataMan is None:
            dm=DM.DataMan(startDate=startDate,obs=cod,freq=freq,db=db)
        else:
            dm=dataMan
            
        self.data=dm.data
        self.fi=dm.future_info

    def a(self, cod='',field=[],out_field=[]):
        data=self.data.loc[self.data['cod']==cod,['date','cod']+field].copy()
        data.reset_index(drop=True, inplace=True)
        d=data[field].pct_change()+1.
        d.loc[0,field]=[1.,1.]
        data[out_field]=d.cumprod()
        return data
    
    
    def b(self, cod='',field=[],out_field=[]):
        data=self.data.loc[self.data['cod']==cod,['date','cod']+field].copy()
        #data[]
       
    def normalize(self,xnp):
        min=xnp.min()
        max=xnp.max()
        _range =max-min
        return (xnp - min) / _range   
    
if __name__=='__main__':
    obs=[]#'A','AP','AG','AU']
    ana=Analysis()
    ana.loadData(dataMan=None, cod=obs, startDate='2020-01-01', freq='1d',db='mongo') 
    data=None
    for c in ana.fi['_id'].unique():
        d=ana.a(cod=c,field=['close','volume'],out_field=['obs_cls','obs_vol'])      
        if data is None:
            data=d
        else:
            data=data.append(d)
    
    fi=ana.fi[['_id',u'同列']]
    data=pd.merge(left=data,right=fi, left_on='cod',right_on='_id',how='left')
    grp_mean=data.groupby(by=[u'同列','date']).mean()
    grp_mean.reset_index(drop=False, inplace=True)
    
    out=None
    for grp in grp_mean[u'同列'].unique():
        print(grp)
        dd=grp_mean.loc[grp_mean[u'同列']==grp,:].copy()
        for f in ['obs_cls','obs_vol']:
            dd[f+'_norm']=ana.normalize(dd[f].values)
            rolling_window=3
            dd[f+'_mov']=[None if i<rolling_window else dd.loc[i-rolling_window:i-1,f+'_norm'].mean() for i in dd.index]
    
            if out is None:
                out=dd
            else:
                out=out.append(dd)
    
    
   
    out['_id']=['%s%s'%(out.loc[i,'date'].values[0],out.loc[i,u'同列'].values[0][:2]) for i in out.index]
    mdbcom.saveBatch('grp_chg', out.to_dict(orient='records'))
    dbcom.creatTableReplaceMany('grp_chg', out)
    #dbcom.replaceManyToMysql('grp_chg', out.to_dict(orient='records'))
    print(1)
    
    
    